import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";
import legacy from "@vitejs/plugin-legacy"; //兼容传统浏览器 内置了core-js regenerator-runtime
import { fileURLToPath, URL } from "node:url"; //更符合vite推荐和 ESM支持
import { viteMockServe } from "vite-plugin-mock";
// https://vite.dev/config/   // command操作命令    mode 当前环境
export default defineConfig(({ mode }) => {
  // eslint-disable-next-line no-undef
  const env = loadEnv(mode, process.cwd()); // 用于该文件  获取 .env文件中创建的环境变量 是个对象
  const isProduction = mode === "production";
  const isDevelop = mode === "develop";
  return {
    base: "/",
    build: {
      outDir: "dist",
      assetsDir: "static",
      sourcemap: isProduction ? "hidden" : true,
      terserOptions: {
        compress: {
          //去除生产的console 和 debugger
          drop_console: isProduction,
          drop_debugger: isProduction,
        },
      },
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes("node_modules")) {
              return "vendor";
            }
          },
        },
      },
      minify: isDevelop ? "esbuild" : "terser", //   轻度/深度
    },
    plugins: [
      react({
        babel: {
          plugins: ["@babel/plugin-proposal-optional-chaining"], //支持可选链
        },
      }),
      legacy({
        targets: ["defaults", "IE 11"],
      }),
      viteMockServe({
        mockPath: "mock", // mock存放目录
        enable: isDevelop && env.VITE_START_MOCK === "true",
        logger: true,
      }),
    ],
    resolve: {
      //路径别名
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
    css: {},
    server: {
      port: 3000,
      open: false,
      proxy: {
        "/service": {
          target: "http://127.0.0.1:5001/",
          // 跨域配置
          changeOrigin: true,
          // 路径重写
          rewrite: (path) => path.replace(/^\/service/, ""),
        },
      },
    },
  };
});
